package main
import (
    "fmt"
    "io/ioutil"
	"net/http"
	"strings"
	"time"
	"strconv"
	"encoding/json"
	"os"
	"bufio"
)
var code_start = [3]string{"0","3","6"}
func httpGet(code string) (string1 string) {
    resp, err := http.Get("http://hq.sinajs.cn/list="+code)
    if err != nil {
		fmt.Printf("get request failed, err:[%s]", err.Error())
		string1 = fmt.Sprintf("%s error", code)
		return
    }
    defer resp.Body.Close()

	bodyContent, err := ioutil.ReadAll(resp.Body)
	// fmt.Println(bodyContent)
	// fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
	// slice01 := strings.Split(string(bodyContent), "=")
	// slice02 := strings.Split(slice01[1], ",")
	// float1,err := strconv.ParseFloat(slice02[3],32)
	// string1 = fmt.Sprintf("%s/%s/%s/%s%%", time.Now().Format("2006-01-02 15:04:05"),string(slice02[1]),string(slice02[2]),string(slice02[3]))
	// string1 = fmt.Sprintf("%s/%s/%s%%", string(slice02[1]),string(slice02[2]),string(slice02[3]))
	// if float1 >= 0.00 {
	// 	fmt.Printf("%c[1;40;31m%s%c[0m", 0x1B, string1, 0x1B)
	// }else{
	// 	fmt.Printf("%c[1;40;32m%s%c[0m", 0x1B, string1, 0x1B)
	// }
	// fmt.Println()
    string1 = string(bodyContent)
    return
}

func http_detail_get(code string) (string1 string){
	body := httpGet(code)
	slice01 := strings.Split(string(body), "=")
	slice02 := strings.Split(slice01[1], ",")
	// float1,err := strconv.ParseFloat(slice02[3],32)
	// string1 = fmt.Sprintf("%s/%s/%s/%s%%", time.Now().Format("2006-01-02 15:04:05"),string(slice02[1]),string(slice02[2]),string(slice02[3]))
	string1 = fmt.Sprintf("%s/%s/%s%%", string(slice02[1]),string(slice02[2]),string(slice02[3]))
	return
}


func get_user_data()(ticket_list []string) {
	// var ticket_data []rune
	// 接收用户输入
	// fmt.Scanln(&ticket_data)
	reader := bufio.NewReader(os.Stdin)
	data, _, _ := reader.ReadLine()
	var ticket_data1 = string(data)
	fmt.Println(ticket_data1)
	// 转义符号
	ticket_data1 = strings.Replace(ticket_data1, "，", ",", -1)
	// fmt.Println(ticket_data)
	ticket_list = removeDuplicateElement(strings.Split(ticket_data1, ","))
	// ticket_list = strings.Split(ticket_data, ",")
	for i := 0; i < len(ticket_list); i++ {
		// fmt.Println(ticket_list[i])
		_,temp_ticket_err := strconv.Atoi(ticket_list[i])  
		// 如果不能转int,或者代码长度不为6则判定失败
		if (temp_ticket_err != nil || (strings.Count(ticket_list[i],"")-1) != 6){
			fmt.Println("Input format error! please retry:")
			ticket_list = get_user_data()
			break
		}
		// 必须以 0/3/6 开头
		var code_bool = false
		for index := 0; index < len(code_start); index++ {
			if (strings.HasPrefix(ticket_list[i], code_start[index])){
				code_bool = true
				break
			}
		}
		if !code_bool{
			fmt.Println("Input data error! Enter code starting with 0/3/6, please retry:")
			ticket_list = get_user_data()
			break
		}
		
		// 检验代码可用性
		resp := httpGet(get_code(ticket_list[i]))
		if strings.Contains(resp, "FAILED") || strings.Contains(resp, "\"\""){
			fmt.Printf("Code error, retry:")
			ticket_list = get_user_data()
			break
		}
		// fmt.Println(ticket_list[i])

	}
	return 
}

func get_code(code string)(code_str string){
	if strings.HasPrefix(code, "6"){
		code_str = "s_sh" + code
	}else{
		code_str = "s_sz" + code
	}
	return
}

func removeDuplicateElement(addrs []string) []string {
    result := make([]string, 0, len(addrs))
    temp := map[string]struct{}{}
    for _, item := range addrs {
        if _, ok := temp[item]; !ok {
            temp[item] = struct{}{}
            result = append(result, item)
        }
    }
    return result
}

func WriteWithIoutil(name,content string) {
    data :=  []byte(content)
    if ioutil.WriteFile(name,data,0644) == nil {
        fmt.Println("Write to file successfully.")
    }
}

type Dict struct{
	Ticket []string  `json:"ticket"`
	Time int `json:"time"`
}

func check_conf(ticket_list []string) []string{
	if len(ticket_list) == 0 {
		fmt.Println("Enter code, separated by half - Angle comma:")
		ticket_list = get_user_data()
		// fmt.Println(ticket_list)
		userModel := get_file_data()
		userModel.Ticket = ticket_list
		// fmt.Println(userModel)
		json_data, err := json.Marshal(&userModel)
		if err != nil {
			fmt.Printf("序列化错误 err is %v", err)
		}
		WriteWithIoutil("./conf.json", string(json_data))
	}else{
		fmt.Println("code: " + strings.Join(ticket_list," ") + ", continue?")
		reader := bufio.NewReader(os.Stdin)
		data, _, _ := reader.ReadLine()
		if string(data) != ""{
			var t []string
			return check_conf(t)
		}
	}
	return ticket_list
}

func get_time() int{
	fmt.Printf("Please enter the interval:")
	reader := bufio.NewReader(os.Stdin)
	data, _, _ := reader.ReadLine()
	userModel := get_file_data()
	if string(data) == ""{
		return userModel.Time
	}
	var time_interval int
	time_interval, err := strconv.Atoi(string(data))  
	if err != nil{
		fmt.Printf("Code error, retry:")
		time_interval = get_time()
	}
	
	userModel.Time = time_interval
	// fmt.Println(userModel)
	json_data, err := json.Marshal(&userModel)
	WriteWithIoutil("./conf.json", string(json_data))
	return time_interval 
}

func get_file_data() Dict{
	file, err := os.Open("./conf.json")
	if err != nil {
		fmt.Println(err)
	  }
	defer file.Close()
	byteValue, _ := ioutil.ReadAll(file)
	userModel := Dict{}
	// fmt.Println(byteValue)

	err1 := json.Unmarshal(byteValue, &userModel)
    if err != nil {
        fmt.Println(err1)
	}
	return userModel
}

func main() {
	userModel := get_file_data()

	// fmt.Println(userModel)

	var ticket_list []string
	ticket_list = userModel.Ticket
	if len(ticket_list) == 0 {
		fmt.Println("The history configuration is empty.")
	}
	ticket_list = check_conf(ticket_list)

	fmt.Println("Interval time is: " + strconv.Itoa(userModel.Time)  + ", Continue or enter the time directly")
	time_interval := get_time()

	fmt.Println("Check order: "+strings.Join(ticket_list," ") + ", Interval time is:" + strconv.Itoa(time_interval))

	var console_str string = ""
	for {
		console_str = time.Now().Format("2006-01-02 15:04:05")
		for index := 0; index < len(ticket_list); index++ {
			console_str = console_str + "   " + http_detail_get(get_code(ticket_list[index]))
		}
		fmt.Println(console_str)
		
		time.Sleep(time.Duration(time_interval)*time.Second)
		
	}
	

    // err := json.Unmarshal([]byte(jsonString), &account)

	// fmt.Printf(string(byteValue))


	// if string(byteValue) == "" {
	// 	fmt.Println("1")
	// }else{
	// 	fmt.Println("2")
	// }
	// for{
	// 	var url = "http://hq.sinajs.cn/list=s_sz002107"
	// 	httpGet(url)		
	// 	time.Sleep(time.Duration(3)*time.Second)
	// }
    
}
